package com.haierp.task;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;
import com.haierp.enums.GeneralStatus;
import com.haierp.model.Inventory;
import com.haierp.model.InventoryListener;
import com.haierp.model.Item;
import com.haierp.model.ItemSku;
import com.haierp.service.IInventoryListenerService;
import com.haierp.service.IInventoryService;
import com.haierp.service.IItemService;
import com.haierp.service.IItemSkuService;
import com.haierp.util.HttpClientUtil;
import com.haierp.util.Md5Util;

import net.sf.json.JSONObject;

/**
 * 根据数据库监听同步库存到有赞
 * @author 朱路
 *
 */
@Component
public class AutoYouzanInventoryTask {
	protected Logger logger = LogManager.getLogger(getClass());

	@Autowired
	private SynInventoryTask synInventoryTask;
	
	@Autowired
	private IInventoryListenerService inventoryListenerService;
	
	@Autowired
	private IItemService itemService;
	
	@Autowired
	private IItemSkuService itemSkuService;
	
	@Autowired
	private IInventoryService inventoryService;
	
	@Scheduled(cron = "0 0/5 * * * ?")
	public void run(){
		int companyId = 1;
		try {
			List<InventoryListener> invents = inventoryListenerService.getInventoryListener(companyId);
			if (CollectionUtils.isNotEmpty(invents)) {
				Set<Long> set = new HashSet<Long>();
				List<InventoryListener> updateListener = Lists.newArrayList();
				for (InventoryListener inventoryListener : invents) {
					if (!set.contains(inventoryListener.getSkuId())) {
						set.add(inventoryListener.getSkuId());
						synInventoryTask.synSkuInventoryListener(inventoryListener);
					} else {
						inventoryListener.setStatus(GeneralStatus.SUCCESS.getCode());
						updateListener.add(inventoryListener);
					}
				}
				if (!updateListener.isEmpty()) {
					synInventoryTask.batchUpdateInventoryListener(updateListener);
				}
			}
		} catch (Exception e) {
			logger.info("AutoYouzanInventoryTask error:"+e);
		}
	}
	/**
	 * 同步小红书库存(关闭)
	 */
	//@Scheduled(cron = "0 0/5 * * * ?")
	public void runOne(){
		int companyId = 2;
		try {
			List<InventoryListener> invents = inventoryListenerService.getInventoryListener(companyId);
			if (CollectionUtils.isNotEmpty(invents)) {
				Set<Long> set = new HashSet<Long>();
				List<InventoryListener> updateListener = Lists.newArrayList();
				for (InventoryListener inventoryListener : invents) {
					if (!set.contains(inventoryListener.getSkuId())) {
						set.add(inventoryListener.getSkuId());
						synInventoryTask.synXhsSkuInventoryListener(inventoryListener);
					} else {
						inventoryListener.setStatus(GeneralStatus.SUCCESS.getCode());
						updateListener.add(inventoryListener);
					}
				}
				if (!updateListener.isEmpty()) {
					synInventoryTask.batchUpdateInventoryListener(updateListener);
				}
			}
		} catch (Exception e) {
			logger.info("AutoxiaohongshuInventoryTask error:"+e);
		}
	}

    /**
     * 推库存到海狐（暂不开放）
     */
	//@Scheduled(cron = "0 0/5 * * * ?")
	public void pushHaiHuInventory() {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("enteCode", "Iruha");
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String timeStamp = dateFormat.format(new Date());
		param.put("timeStamp", timeStamp);
		String mysign = Md5Util.getMD5("enteCode=haihuhaitao&timeStamp=" + timeStamp);
		param.put("sign", mysign);
		EntityWrapper<Item> entityWrapper = new EntityWrapper<>();
		entityWrapper.where("is_sale = {0}", 1);
		entityWrapper.and("third_sale = {0}", 1);
		List<Map<String, Object>> itemList = new ArrayList<Map<String, Object>>();
		List<Item> itemListTemp = itemService.selectList(entityWrapper);
		for (Item item : itemListTemp) {
			Map<String, Object> paramItem = new HashMap<String, Object>();
			paramItem.put("name", item.getName());
			paramItem.put("itemCode", item.getItemCode());
			EntityWrapper<ItemSku> entityWrapperOne = new EntityWrapper<>();
			entityWrapperOne.where("item_id = {0}", item.getId());
			List<Map<String, Object>> itemSkuList = new ArrayList<Map<String, Object>>();
			List<ItemSku> ItemSkuListTemp = itemSkuService.selectList(entityWrapperOne);
			for (ItemSku itemSku : ItemSkuListTemp) {
				Map<String, Object> paramItemSku = new HashMap<String, Object>();
				Inventory inventory = inventoryService.queryInventoryBySkuId(item.getId(), itemSku.getId());
				paramItemSku.put("skuCode", itemSku.getSkuCode());
				if (inventory != null) {
					paramItemSku.put("itemskuQuantity", inventory.getTotalAvailableInv());
				}
				itemSkuList.add(paramItemSku);
			}
			paramItem.put("itemSkuList", itemSkuList);
			itemList.add(paramItem);
		}
		param.put("itemList", itemList);
		//System.out.println(param);
		logger.info("海狐推库存参数："+param);
		JSONObject post = HttpClientUtil.post("http://expressjob.haihu.com/erp/product", null, param,"1");
		System.out.println(post);
	}
}
